import React, {createContext, useReducer, useContext} from 'react';

type Action = {type: 'true'} | {type: 'false'};
type Dispatch = (action: Action) => void;
type ProviderProps = {
  children: React.ReactNode;
};

// 创建context用来传递数据的
const ScrollContext = createContext<{
  isScroll: Boolean;
  dispatch: Dispatch;
} | null>(null);

// 更改数据的一些具体动作
const scrollReducer = (state: Boolean, action: Action) => {
  switch (action.type) {
    case 'true':
      return true;
    case 'false':
      return false;
    default:
      throw new Error('Unhandle action type of reducer');
  }
};

// 创建父组件并传递数据，和更改数据的函数
const ScrollProvider = ({children}: ProviderProps) => {
  const [isScroll, dispatch] = useReducer(scrollReducer, false);
  // 在 context 中共享 state 与 dispatch
  const value = {isScroll, dispatch};

  return (
    <ScrollContext.Provider value={value}>{children}</ScrollContext.Provider>
  );
};

const useisScroll = () => {
  const context = useContext(ScrollContext);
  if (context == undefined)
    throw new Error('useisScroll must be used within a context ScrollProvider');
  return context;
};

export {ScrollProvider, ScrollContext, useisScroll};
